package com.stores.toolset;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class WebAction {
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;

	/**
	 * 
	 * @param request
	 */
	public WebAction(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * 
	 * @param request
	 * @param response
	 */
	public WebAction(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/***
	 * 
	 * @param response
	 * @param responseText
	 */
	public void writeResponse(String responseText) {
		PrintWriter writer;
		try {
			writer = this.response.getWriter();
			writer.print(responseText);
		} catch (IOException e) {
		}
	}

	/***
	 * 
	 * @param response
	 * @param data
	 */
	public void writeJsonResponse(Object data) {
		PrintWriter writer;
		try {
			Gson gson = new Gson();
			writer = this.response.getWriter();
			writer.print(gson.toJson(data));
		} catch (IOException e) {
		}
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	public String getJson() {
		StringBuilder jsonBuilder = new StringBuilder();
		BufferedReader reader;
		try {
			reader = this.request.getReader();
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					jsonBuilder.append(line);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}

		return jsonBuilder.toString();
	}

	/***
	 * 
	 * @param <T>
	 * @param json
	 * @param t
	 * @return
	 */
	public <T> T parseJson(String json, Class<T> t) {
		Gson gson = new Gson();
		return gson.fromJson(json, t);
	}

	/***
	 * 
	 * @param request
	 * @param t
	 * @return
	 */
	public <T> T parseJsonRequest(Class<T> t) {
		String json = this.getJson();
		return this.parseJson(json, t);
	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	public boolean isUrl(String url) {
		String requestUrl = this.request.getServletPath();
		return requestUrl.equalsIgnoreCase(url);
	}
}
